package com.example.securtydemo.permission.service.impl;

import com.example.securtydemo.permission.bean.Permission;
import com.example.securtydemo.permission.bean.Role;
import com.example.securtydemo.permission.repository.PermissionRepository;
import com.example.securtydemo.permission.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.*;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionRepository permissionRepository;

    private Map<String, Collection<ConfigAttribute>> permissionMap = null;

    @PostConstruct
    /**
     * 从数据库中获取所有权限信息，然后进行遍历，存储到permissionMap集合中
     */
    public void initPermissions() {
        permissionMap = new HashMap<>();
        List<Permission> permissions = permissionRepository.findAll();
        for (Permission p : permissions) {
            Collection<ConfigAttribute> collection = new ArrayList<ConfigAttribute>();
            for (Role role : p.getRoles()) {
                ConfigAttribute configAttribute = new SecurityConfig("ROLE_" + role.getName());
                collection.add(configAttribute);
            }
            permissionMap.put(p.getUrl(), collection);
        }
        System.out.println(permissionMap);
    }

    @Override
    public Map<String, Collection<ConfigAttribute>> getPermissionMap() {
        if (permissionMap == null || permissionMap.size() == 0) {
            initPermissions();
        }
        return permissionMap;
    }
}
